package com.lai.note.controller.user;


import com.google.gson.Gson;
import com.lai.note.dto.MessageBean;
import com.lai.note.dto.PasswordDto;
import com.lai.note.dto.UserDto;
import com.lai.note.exception.*;
import com.lai.note.model.User;
import com.lai.note.service.UserBaseService;
import com.lai.note.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;


/**
 * Created by Lai on 2021/6/5.
 */
@RestController
@RequestMapping("/user/base")
@Validated
public class UserBaseAction {

    @Autowired
    private UserBaseService userBaseService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;


    @Autowired
    public void setUserBaseService(UserBaseService userBaseService) {
        this.userBaseService = userBaseService;
    }

    @Autowired
    public void setRedisTemplateUtil(RedisTemplateUtil redisTemplateUtil) {
        this.redisTemplateUtil = redisTemplateUtil;
    }




    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 根据手机号获取验证码
     * @param phone
     * @return
     */
    @RequestMapping(value = "/getCode.action",method = RequestMethod.GET)
    public MessageBean getCode(@NotBlank(message = "手机号不能为空")@RequestParam("phone") @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号码格式错误") String phone){
        String code = RandomUtil.getRandomNum();
//        阿里云短信发送
//        try {
//            if (AliMsgUtil.sendCode(phone, code))
        redisTemplateUtil.set(phone,code,5*60);
//        } catch (ClientException e) {
//            e.printStackTrace();
//           return MessageUtil.failureBack();
//        }
        return MessageUtil.success(code);
    }


    /**
     * 注册
     * @param phone
     * @param code
     * @param loginPwd
     * @param confirmPwd
     * @return
     */
    @RequestMapping(value = "/register.action",method = RequestMethod.POST)
    public MessageBean userRegister(@NotBlank(message = "手机号不能为空") @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号码格式错误") String phone,
                                    @NotBlank(message = "验证码不能为空") String code,
                                    @NotBlank(message = "密码不能为空") String loginPwd,
                                    @NotBlank(message = "密码不能为空") String confirmPwd,
                                    @NotNull(message = "经度不能为空") Double lng,
                                    @NotNull(message = "纬度不能为空") Double lat){
        if (!loginPwd.equals(confirmPwd))
            return MessageUtil.failure("两次输入的密码不一致");
        String redisCode = (String) redisTemplateUtil.get(phone);
        if (!code.equals(redisCode)){
            logger.info("code:"+code+"  redisCode: "+redisCode);
            return MessageUtil.failure("验证码错误");
        }

        User user = null;
        try {
            user = userBaseService.userRegister(phone,loginPwd,lng,lat);
        } catch (UserExistException e) {
            return MessageUtil.failure("该手机号已被注册");
        }
        return MessageUtil.success(user);
    }

    /*获取用户基本信息*/
    @RequestMapping(value = "/getUserInfo.action",method = RequestMethod.GET)
    public MessageBean getUserInfo(HttpSession session){
//        Object user = session.getAttribute("user");
        User user = (User) session.getAttribute("user");
        if(user!=null){
            user = userBaseService.findUserById(user.getUserId());
        }else{
            return MessageUtil.failure("用户不存在-_-");
        }
        return MessageUtil.success(user);
    }

    /**
     * 更新用户的基本信息
     * @return
     */
    @RequestMapping(value = "/updateUser.action",method = RequestMethod.PUT)
    public MessageBean updateUser(String userJson){
//        System.out.println(userDto);
//        User user = null;

        User user = null;
        UserDto userDto = new Gson().fromJson(userJson, UserDto.class);
        System.out.println("userDto:-->"+userDto);
        try {
            user = userBaseService.updateUser(userDto);
        } catch (DataUpdateFailureException e) {
            return MessageUtil.failureDataUpdate();
        } catch (UserNotExistException e){
            return MessageUtil.failure("用户不存在");
        }
        return MessageUtil.success(user);
    }

    /**
     *账号密码登录
     * @param phone 手机号
     * @param pwd 密码
     * @return
     */
    @RequestMapping(value = "/loginByPwd.action",method = RequestMethod.POST)

    public MessageBean userLoginByPwd(@NotBlank(message = "手机号不能为空") String phone,
                                      @NotBlank(message = "密码不能为空")String pwd,
                                      HttpSession session, HttpServletResponse response){
        User user =null;
        try {
             user = userBaseService.userLoginByPwd(phone, SHA256Utils.getSHA256(pwd));
        } catch (NoPassIdentityException e) {
            return MessageUtil.failureFront("用户名或者密码错误");
        } catch (UserNotExistException e) {
            return MessageUtil.failure("该用户尚未注册");
        }
//
//        TokenInfo token = new TokenInfo(user.getUserId(), user.getUserPhone(), user.getUserName());
//        String jwt = JWTUtils.generateToken(JSONUtils.objToJson(token));
//        CookieUtils.setCookie(response, UserConstant.HEADER_STRING, jwt, UserConstant.COOKIEMAXAGE, true);

        System.out.println(user.toString());
        session.setAttribute("user",user);
        return MessageUtil.success(user);
    }

    /**
     * 验证码登录
     * @param phone 手机号
     * @param code 验证码
     * @return
     */
    @RequestMapping(value = "/loginByCode.action",method = RequestMethod.POST)
    public MessageBean userLoginByCode(@NotBlank(message = "手机号不能为空") String phone, @NotBlank(message = "验证码不能为空")String code, HttpSession session){
        User user =null;
        try {
            user = userBaseService.userLoginByCode(phone, code);
        } catch (UserNotExistException e) {
            return MessageUtil.failure("该用户尚未注册");
        } catch (IdentifyingCodeException e) {
            return MessageUtil.failureFront("验证码错误");
        }
        session.setAttribute("user", user);
        return MessageUtil.success(user);
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "/logout.action",method = RequestMethod.POST)
    public MessageBean userLogout(HttpSession session){
        session.invalidate();
        return MessageUtil.success();
    }


    /**
     * 通过旧密码修改新密码
     * @param userId 用户id
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return
     */

    /**
     * 通过旧密码修改新密码   json形式
     * @param passwordDto
     * @return
     */
    @RequestMapping(value = "/updateUserLoginPwdByOldPwd.action",method = RequestMethod.PUT)
    public MessageBean updateUserLoginPwdByOldPwd(@RequestBody @Valid PasswordDto passwordDto){
        try {
            userBaseService.updateUserLoginPwdByOldPwd(passwordDto.getUserId(),passwordDto.getOldPwd(),passwordDto.getNewPwd());
        } catch (NoPassIdentityException e) {
            return MessageUtil.failure("原密码错误,请重试");
        }

        return MessageUtil.success();
    }

    /**
     * 通过验证码修改新密码
     * @return
     */
    @RequestMapping(value = "/updateUserLoginPwdByCode.action",method = RequestMethod.POST)
    public MessageBean updateUserLoginPwdByCode(@NotBlank(message = "手机号不能为空")String phone,
                                                @NotBlank(message = "验证码不能为空")String code, @NotBlank(message = "新密码不能为空")String newPwd){
        try {
            userBaseService.updateUserLoginPwdByCode(phone,code,newPwd);
        } catch (IdentifyingCodeException e) {
            return MessageUtil.failure("验证码错误");
        }
        return MessageUtil.success();
    }


    /**
     * 获取七牛云上传token
     *
     * @param uploadType 0代表不覆盖上传，1代表覆盖上传
     * @param key        如果uploadtType为1，则key定有值，代表覆盖的文件名
     * @return
     */
    @RequestMapping(value = "/getUpToken.action", method = RequestMethod.GET)
    public MessageBean getUpToken(@NotNull(message = "上传类型不能为空") Integer uploadType, String key) {
        return MessageUtil.success("操作成功", QiniuUtil.getUpToken(uploadType,key));
    }



    @RequestMapping(value = "/isFirstLogin.action", method = RequestMethod.GET)
    public MessageBean isFirstLogin(HttpSession session) {
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        if (user!= null&&!CheckNull.isNull(user.getEmail()))
            return MessageUtil.success();
        return MessageUtil.failure();
    }

    @RequestMapping(value = "/isLogined.action",method = RequestMethod.GET)
    public MessageBean isLogined(HttpSession session){
        try{
            User user = (User) session.getAttribute("user");
            if(user!=null)
                return MessageUtil.success("登录成功*_*");
            else
                return MessageUtil.failure("登录失败-_-");
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


}
